<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Layout {

    var $ci;
    var $layout;
    var $controller;
    var $view;
    var $method;
    var $js;
    var $css;
    var $base_url;
    var $folder="";
    private $block_list, $block_new, $block_replace = false;

    public function Layout($layout = "default"){

        $this->ci  =& get_instance();
        $this->layout = $layout;
        $this->controller = $this->ci->router->fetch_class();
        $this->method = $this->ci->router->fetch_method();
        $this->view = "{$this->controller}/{$this->method}";
    }

    function setLayout($layout,$folder=""){
        if(!empty($folder)){
            $this->folder = $folder;
            $this->view = "{$folder}/{$this->controller}/{$this->method}";
        }else {
            $this->folder="";
        }
        $this->layout = $layout;
    }

    function view($data=null, $return=false){
        $loadedData['content_for_layout'] = $this->ci->load->view($this->view,$data,true);
        $loadedData['append_js']= $this->js;
        $loadedData['append_css']= $this->css;
        $this->block_replace = true;
        //$output = $this->obj->load->view($this->layout_view, $data, $return);
        if($return):
            $output = $this->ci->load->view('layouts/'.$this->layout, $data, $return);
            return $output;
        else:
            if(!empty($this->folder)){
                $this->ci->load->view($this->folder.'/layouts/'.$this->layout, $loadedData, false);
            }else {
                $this->ci->load->view('layouts/'.$this->layout, $loadedData, false);
            }
        endif;
    }

    function js($item){
        $this->js .= sprintf('<script type="text/javascript" src="%s"></script>', $item)."\n";
    }
    function css($item){
        $this->css .= sprintf('<link rel="stylesheet" type="text/css"  href="%s" />', $item)."\n";
    }

    function block($name = '') {
        if ($name != '') {
            $this->block_new = $name;
            ob_start();
        } else {
            if ($this->block_replace) {
                // If block was overriden in template, replace it in layout
                if (!empty($this->block_list[$this->block_new])) {
                    ob_end_clean();
                    echo $this->block_list[$this->block_new];
                }
            } else {
                $this->block_list[$this->block_new] = ob_get_clean();
            }
        }
    }

}
?>